<template>
    <div>
        <div class="e-form" v-if="dialogVisible === false">
            <div class="tabs">
                <div class="tabs-title">基本信息</div>
                <div style="width: 100%" class="form">
                    <el-form
                        :model="formData"
                        label-width="170px"
                        :rules="rules"
                        ref="ruleForm"
                    >
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="补遗编号" width="230">
                                    <!-- <span>{{ formData.billNo }}</span> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="补遗日期" width="230">
                                    <el-date-picker
                                        v-model="formData.changeDate"
                                        type="date"
                                        placeholder="选择日期"
                                        :clearable="false"
                                        value-format="yyyy-MM-dd"
                                    >
                                    </el-date-picker
                                    >>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="招标编号"
                                    width="230"
                                    prop="billNo"
                                >
                                    <span>{{ formData.tenderApplyNo }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    label="招标人"
                                    width="230"
                                    prop="tenderUser"
                                >
                                    <ComInputSelectUnit
                                        :orgName.sync="formData.tenderUser"
                                        :orgId.sync="formData.tenderUserId"
                                        :SelectedIDs="
                                            formData.tenderUserId !== ''
                                                ? [formData.tenderUserId]
                                                : []
                                        "
                                        type="getParentOrg"
                                    />
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <!-- 需要id和name -->
                                <el-form-item
                                    label="申请单位"
                                    width="230"
                                    prop="applyOrgName"
                                >
                                    <ComInputSelectUnit
                                        :orgName.sync="formData.applyOrgName"
                                        :orgId.sync="formData.applyOrgId"
                                        :SelectedIDs="
                                            formData.applyOrgId !== ''
                                                ? [formData.applyOrgId]
                                                : []
                                        "
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="录入机构" prop="orgName">
                                    <span>{{ formData.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="招标方式"
                                    prop="tenderForm"
                                >
                                    <el-select
                                        v-model="formData.tenderForm"
                                        placeholder="请选择"
                                        @change="
                                            selectChange($event, '招标方式')
                                        "
                                    >
                                        <el-option
                                            v-for="item in options.tenderForm"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="申请日期" prop="applyTime">
                                    <el-date-picker
                                        v-model="formData.applyTime"
                                        type="date"
                                        placeholder="选择日期"
                                        :clearable="false"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="服务类型："
                                    prop="tenderClass"
                                >
                                    <span>{{
                                        formData.tenderClass | tenderClass(this)
                                    }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    label="招标类型："
                                    prop="machineType"
                                >
                                    <el-select
                                        v-model="formData.machineType"
                                        placeholder="请选择"
                                    >
                                        <el-option
                                            v-for="(
                                                item, index
                                            ) in options.machineType2"
                                            :key="index + 1"
                                            :label="item"
                                            :value="index + 1"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="拟招标项目名称"
                                    width="200"
                                    prop="tenderName"
                                >
                                    <el-input
                                        v-model="formData.tenderName"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                    label="拟招标金额（元）"
                                    width="200"
                                    prop="tenderAmount"
                                >
                                    <span>{{ formData.tenderAmount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="投标保证金（元）"
                                    prop="tenderBail"
                                >
                                    <el-input
                                        v-model="formData.tenderBail"
                                        v-enterJustFloat
                                        @blur="
                                            inputblur(formData, 'tenderBail')
                                        "
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="税额" prop="">
                                    <span>{{ formData.taxAmount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="购买标书费用（元）"
                                    prop="bidCharge"
                                >
                                    <el-input
                                        v-model="formData.tenderFee"
                                        v-enterJustFloat
                                        @blur="inputblur(formData, 'tenderFee')"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="币种" prop="currencyId">
                                    <el-select
                                        v-model="formData.currencyId"
                                        placeholder="请选择"
                                        @change="selectChange($event, '币种')"
                                    >
                                        <el-option
                                            v-for="item in options.currency"
                                            :key="item.kvValue"
                                            :label="item.kvKey"
                                            :value="item.kvValue"
                                        >
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="投标截止时间"
                                    prop="tenderEndTime"
                                >
                                    <el-date-picker
                                        v-model="formData.tenderEndTime"
                                        type="datetime"
                                        placeholder="选择日期时间"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                    >
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态">
                                    <span>草稿</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item
                                    label="招标公告"
                                    prop="tenderNotice"
                                    v-if="
                                        formData.tenderForm !== '2' &&
                                        formData.tenderForm !== '4'
                                    "
                                >
                                    <el-button
                                        style="width: 222px"
                                        class="btn-greenYellow"
                                        @click="handleNotice"
                                        >招标公告</el-button
                                    >
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-form-item
                                label="招标需求陈述"
                                prop="purchaseDemandStatement"
                            >
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入内容"
                                    v-model="formData.purchaseDemandStatement"
                                    style="margin-right: 110px"
                                >
                                </el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-form-item label="变更原因" prop="changeReason">
                                <el-input
                                    type="textarea"
                                    :rows="2"
                                    placeholder="请输入内容"
                                    v-model="formData.changeReason"
                                    style="margin-right: 110px"
                                >
                                </el-input>
                            </el-form-item>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币" prop="baseCurName">
                                    <!-- 传id和名称 -->
                                    <span>{{ formData.baseCurName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col
                                :span="12"
                                v-if="
                                    formData.baseCurName !== formData.currency
                                "
                            >
                                <el-form-item label="人民币汇率" prop="rmbRate">
                                    <span>{{ formData.rmbRate }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <!-- <el-row>
                            <el-col :span="12">
                                <el-form-item label="拟招标金额（本位币）">
                                    <span>{{ formData.tenderAmount }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row> -->
                    </el-form>
                </div>
            </div>
            <div class="buttons">
                <el-button type="primary" class="btn-blue" @click="submit"
                    >保存</el-button
                >
                <el-button @click="handleClose">取消</el-button>
            </div>
        </div>
        <!-- dialog -->
        <ComNoticeDialog
            ref="ComNoticeDialog"
            :dialogVisible.sync="dialogVisible"
            :tenderClass="parseInt(formData.tenderClass)"
            :tenderForm="String(formData.tenderForm)"
            v-if="Object.keys(formData).length !== 0"
            :content="formData.tenderNotice"
            @save="noticeSave"
        />
    </div>
</template>

<script>
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import ComPagination from '@/components/pagination/pagination.vue'
// import tenderRequest from '@/api/tender/tender.js'
// import applyRequest from '@/api/tender/apply.js'
import materialMachineIncomeRequest from '@/api/tender/materialMachineIncome.js'
import ComNoticeDialog from '@/components/common/noticeDialog.vue'
// import ComShowBiddingButton from '@/pages/bidding/common/showBiddingButton.vue'
import ComInputSelectUnit from '@/pages/bidding/common/inputSelectUnit.vue'
import { mapState } from 'vuex'

export default {
    data () {
        const not0RmbRate = (rule, value, callback) => {
            if (typeof value === 'number' && value === 0) {
                return callback(new Error('人民币汇率不能为0'))
            } else {
                callback()
            }
        }
        const greaterZero = (rule, value, callback) => {
            if (typeof value === 'number' && value < 0) {
                return callback(new Error('不能为负数'))
            } else {
                callback()
            }
        }
        return {
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            formData: {
                applyOrgId: '',
                applyOrgName: '',
                applyTime: '',
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurTenderAmount: 0,
                billId: '',
                billNo: '',
                changeReason: '',
                count: 0,
                currency: '',
                currencyId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                lastModifierId: '',
                lastModifierName: '',
                lastModifyTime: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                purchaseDemandStatement: '',
                releaseState: 0,
                remarks: '',
                rmbRate: 0,
                machineType: 0,
                state: 0,
                taxAmount: 0,
                tenderAmount: 0,
                tenderApplyId: '',
                tenderApplyNo: '',
                tenderBail: 0,
                tenderClass: 0,
                tenderEndTime: '',
                tenderFee: 0,
                tenderForm: '',
                tenderName: '',
                tenderNotice: '',
                tenderState: 0,
                tenderUser: '',
                tenderUserId: '',
                tenderUserName: '',
                version: 0,
                workId: ''
            },
            test: '',
            selectData: [],
            selectTableColumnAttr: [
                {
                    label: '机构Id',
                    prop: 'orgId'
                },
                {
                    label: '机构名称',
                    prop: 'orgName'
                }
            ],
            selectTableColumnWidth: {
                leftWidth: '150',
                rightWidth: '100'
            },
            selectDataPagination: {},
            dialogVisible: false,
            rules: {
                billNo: {
                    required: true,
                    message: '请输入招标编号',
                    trigger: 'blur'
                },
                tenderName: {
                    required: true,
                    message: '请输入拟招标项目名称',
                    trigger: 'blur'
                },
                tenderForm: {
                    required: true,
                    message: '请选择招标方式',
                    trigger: 'change'
                },
                tenderType: {
                    required: true,
                    message: '请选择招标类型',
                    trigger: 'change'
                },
                projectName: {
                    required: true,
                    message: '请输入项目名称',
                    trigger: 'blur'
                },
                tenderNotice: {
                    required: true,
                    message: '请输入公告',
                    trigger: 'change'
                },
                tenderBail: [
                    {
                        required: true,
                        message: '请输入投标保证金（元）',
                        trigger: 'blur'
                    },
                    // { type: 'number', message: '保证金必须为数字值' },
                    { validator: greaterZero, trigger: 'blur' }
                ],
                currencyId: {
                    required: true,
                    message: '请选择币种',
                    trigger: 'change'
                },
                tenderAmount: {
                    required: true,
                    message: '请输入拟招标金额（元）',
                    trigger: 'blur'
                },
                taxAmount: {
                    required: true,
                    message: '请输入税额',
                    trigger: 'blur'
                },
                applyTime: {
                    required: true,
                    message: '请选择申请日期',
                    trigger: 'change'
                },
                tenderState: {
                    required: true,
                    message: '请输入招标状态',
                    trigger: 'blur'
                },
                state: {
                    required: true,
                    message: '请输入申请状态',
                    trigger: 'blur'
                },
                applyOrgName: {
                    required: true,
                    message: '请选择申请单位',
                    trigger: 'change'
                },
                projectOverview: {
                    required: true,
                    message: '请输入招标项目工程概况',
                    trigger: 'blur'
                },
                remarks: [
                    // { required: true, message: '请输入备注', trigger: 'blur' },
                    {
                        max: 500,
                        message: '最多允许输500个汉字',
                        trigger: 'blur'
                    }
                ],
                orgName: {
                    required: true,
                    message: '请输入录入机构',
                    trigger: 'blur'
                },
                tenderUser: {
                    required: true,
                    message: '请选择招标人',
                    trigger: 'change'
                },
                baseCurName: {
                    required: true,
                    message: '没有设置本位币，请联系集团信息化管理员设置！',
                    trigger: 'blur'
                },
                rmbRate: [
                    {
                        required: true,
                        message: '请选择币种',
                        trigger: 'change'
                    },
                    { validator: not0RmbRate, trigger: 'change' }
                ],
                centralizedPurchasingState: {
                    required: true,
                    message: '请选择集中招标',
                    trigger: 'change'
                },
                tenderFee: {
                    required: true,
                    message: '请输入购买标书费用',
                    trigger: 'blur'
                },
                tenderEndTime: {
                    required: true,
                    message: '请选择投标截止时间',
                    trigger: 'change'
                },
                pushPurchasePlatformState: {
                    required: true,
                    message: '请选择发布到招采平台',
                    trigger: 'change'
                },
                purchaseDemandStatement: {
                    required: true,
                    message: '请输入招标需求陈述',
                    trigger: 'blur'
                },
                changeReason: [
                    {
                        required: true,
                        message: '请输入变更原因',
                        trigger: 'blur'
                    },
                    {
                        min: 1,
                        max: 500,
                        message: '最多允许输入500个汉字',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.$route.query.tenderId || this.$route.query.billid
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile,
        // ComPagination,
        ComNoticeDialog,
        // ComShowBiddingButton,
        ComInputSelectUnit
    },
    created () {
        // 获取招标基础信息
        this.getTenderData()
        // ;(async () => {
        //     const data = {}
        //     data.billId = this.tenderId
        //     await this.tenderApplyFindById(data)
        //     // this.getVuexData()
        //     this.getNowDate()
        // })()
        console.log('formData', this.formData)
    },
    mounted () {},
    beforeDestroy () {
        this.$notify.closeAll()
    },
    methods: {
        inputblur (row, val) {
            row[val] = isNaN(parseFloat(row[val])) ? 0 : parseFloat(row[val])
        },
        noticeSave (content) {
            this.formData.tenderNotice = content
        },
        handleNotice () {
            this.dialogVisible = true
        },
        openNewPage (name) {
            this.$notify.closeAll()
            if (name === 'OrgSelectData') {
                const params = JSON.stringify({
                    // 正式环境应该不用转换
                    title: '申请机构',
                    url: '/hr/org/getChildrenOrg',
                    method: 'get',
                    params: { orgId: this.$store.state.userInfo.orgInfo.orgId },
                    tableColumnAttr: this.selectTableColumnAttr,
                    tableColumnWidth: this.selectTableColumnWidth,
                    ifPagination: 0
                })
                this.$notify({
                    title: '申请机构',
                    dangerouslyUseHTMLString: true,
                    message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/selectData?params=${params}</textarea>
                <br><br>
                回调参数：<br>
                <textarea cols="35" rows="3" id="callBackData"></textarea><br>
                <button id="getPopData">执行回调方法</button>
                `,
                    duration: 0
                })
                document
                    .querySelector('#getPopData')
                    .addEventListener('click', this.getPopData)
            }
        },
        getPopData () {
            const callBackData = JSON.parse(
                document.querySelector('#callBackData').value
            )
            this.formData.applyOrgId = callBackData.orgId
            this.formData.applyOrgName = callBackData.orgName
        },
        selectChange (kvId, label) {
            if (label === '招标方式') {
                this.options.tenderForm.forEach(item => {
                    if (kvId === item.value) {
                        this.formData.tenderFormName = item.label
                    }
                })
            } else if (label === '币种') {
                this.options.currency.forEach(item => {
                    if (item.kvValue === kvId) {
                        this.formData.currency = item.kvKey
                    }
                })
            } else if (label === '目标预算') {
                ('等待接口')
            }
        },
        showBidding () {
            if (!this.tenderId) return // 前期需求可切换，现在不需要
            this.$notify.closeAll()
            this.$notify({
                title: '查看招标详情',
                dangerouslyUseHTMLString: true,
                message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/biddingApplicationShow?tenderId=${this.tenderId}</textarea>
                `,
                duration: 0
            })
            // this.$router.push({
            //     path: './biddingApplicationShow',
            //     query: { tenderId: this.tenderId }
            // })
        },
        async getTenderData (data) {
            data
            await materialMachineIncomeRequest
                .applyGetById({ id: this.tenderId })
                .then(res => {
                    // 表单提交信息映射基础招标信息
                    const tenderData = res
                    Object.keys(this.formData).forEach(formDataKey => {
                        Object.keys(tenderData).forEach(tenderDataKey => {
                            if (formDataKey === tenderDataKey) {
                                this.formData[formDataKey] =
                                    tenderData[tenderDataKey]
                            }
                        })
                    })
                    // 部分数据对应不上，需要增改
                    this.formData.changeDate = this.getNowDate()
                    this.formData.purchaser = res.tenderUser
                    this.formData.founderName =
                        this.$store.state.userInfo.userName
                    this.formData.founderId = this.$store.state.userInfo.userId
                    // this.formData.tenderUser = this.$store.state.userInfo.orgInfo.orgName
                    // this.formData.tenderUserId = this.$store.state.userInfo.orgInfo.orgId
                    this.formData.tenderApplyId = tenderData.billId
                    this.formData.state = 0
                    // tenderApplyNo和billNo都是招标单据的编号
                    this.formData.tenderApplyNo = tenderData.billNo
                    delete this.formData.billId // 新增不需要表单的billId
                    delete this.formData.workId // 新增不需要基础信息的workId
                    // delete this.formData.billNo
                })
        },
        noFocus () {
            this.$refs.noFocus1.blur()
            this.$refs.noFocus2.blur()
        },
        submit () {
            this.$refs.ruleForm.validate(valid => {
                if (valid) {
                    materialMachineIncomeRequest
                        .changeCreate(this.formData)
                        .then(res => {
                            const callBack = () => {
                                this.$router.push({
                                    path: './machineTenderAddendumEdit',
                                    query: {
                                        billid: res,
                                        tenderId: this.tenderId
                                    }
                                })
                            }
                            const cancelCallBack = () => {
                                this.$router.push({
                                    path: './machineBiddingApplicationEdit',
                                    query: {
                                        billid: this.tenderId,
                                        seat: 'recodes'
                                    }
                                })
                            }
                            this.clientPop(
                                'suc',
                                '保存成功，是否继续？',
                                callBack,
                                null,
                                cancelCallBack
                            )
                        })
                }
            })
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            return nowtime
            // this.$set(this.formData, 'gmtCreate', nowtime)
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        handleClose () {
            this.$router.push({
                path: './machineBiddingApplicationEdit',
                query: { billid: this.tenderId, seat: 'recodes' }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    padding: 0 20px;
    /* .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    } */
}
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;

    /* .top {
    .left {
      padding: 20px;
      padding-top: 0px;
    }
  } */
}

.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}
.el-tab-pane {
    margin-left: -10px;
}
</style>
